<template>
  <div id="blog-live2d--wrap">
    <div class="blog-live2d--menu">
      <span @click="changeModel"><i class="el-icon-refresh"></i></span>
      <span @click="changeTextures"><i class="el-icon-shopping-bag-2"></i></span>
    </div>
    <canvas id="live2d" width="250" height="500">
    </canvas>
  </div>
</template>

<script>
const GET_URL = 'https://live2d.fghrsh.net/api/get/'
const MODEL_URL = 'https://api.fghrsh.net/live2d/switch/?id'
const TEXTURES_URL = 'https://api.fghrsh.net/live2d/rand_textures/?id'
const LIVE2D_MODEL_NAME = 'ua_live2d_mid'
import '@/static/live2D/js/live2d'
import axios from 'axios'
import store from 'store'
export default {
  components:{},
  data(){
    return {
      modeId: 1,
      texturesId: 22
    }
  },
created(){
  let {modeId, texturesId} = store.get(LIVE2D_MODEL_NAME)
  this.modeId = modeId
  this.texturesId = texturesId
},
mounted(){
  this.loadModel();
},
watch:{},
computed:{},
methods:{
  async changeModel() {
    if (this.modeId === 4 || this.modeId === 5)
    {
      this.modeId = 1;
    }
    try {
      let result = await axios.get(`${MODEL_URL}=${this.modeId}`)
      this.modeId = result.data?.model.id
      this.loadModel()
    }
    catch(err)
    {
      this.resetModel();
    }
  },
  async changeTextures() {
    try {
      let result = await axios.get(`${TEXTURES_URL}=${this.texturesId}`)
      this.texturesId = result.data?.textures.id
      this.loadModel()
    }
    catch(err)
    {
      this.resetModel();
    }
  },
  loadModel() {
    loadlive2d('live2d',`${GET_URL}?id=${this.modeId}-${this.texturesId}`)
    store.set(LIVE2D_MODEL_NAME, {
      modeId: this.modeId,
      texturesId: this.texturesId
    })
  },
  resetModel() {
    this.modeId = 1;
    this.texturesId = 22;
    this.loadModel();
  }
},
}
</script>
<style lang="scss" scoped>
#blog-live2d--wrap {
  position: fixed;
  bottom: 15px;
  width: 300px;
  height: 500px;
}

.right {
  right: 0
}
.blog-live2d--menu {
  position: absolute;
  left: 20px;
  bottom: 50%;
  display: none;
  width: 20px;
  flex-direction: column;
  align-items: center;
  background-color: #fff;
  padding: 10px;
  border-radius: 8px;
  span {
    line-height: 25px;
    cursor: pointer;
  }
}

#blog-live2d--wrap:hover .blog-live2d--menu {
  display: flex;
}
</style>